<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { watchDebounced } from '@vueuse/core'
import { searchRoomsByName, getRoomList } from '@/api/chat'
import useSafeAreaInsets from '@/composables/useSafeAreaInsets'
import useMenuButtonRect from '@/composables/useMenuButtonRect'
import useLocale from '@/composables/useLocale'

const props = defineProps({
    archive: {
        type: [Number, String],
        default: 0,
    },
})

const roomList = ref([])
const safeAreaInsets = useSafeAreaInsets()
const menuButton = useMenuButtonRect()

const searchInput = ref('')
const { t } = useLocale()

onLoad(async () => {
    uni.showLoading()
    const resp = await getRoomList({ archive: props.archive || 0 })
    uni.hideLoading()
    roomList.value = resp?.content ?? []
})

function goBack() {
    uni.navigateBack()
}

const searchResult = ref([])
const showRoomList = computed(() => {
    if (searchInput.value.length > 0) {
        return searchResult.value
    } else {
        return roomList.value
    }
})
async function fetchRooms() {
    if (!searchInput.value) {
        return
    }
    try {
        const resp = await searchRoomsByName({
            archive: props.archive ?? 0,
            roomName: searchInput.value,
        })
        searchResult.value = resp
    } catch (_) {
        /* empty */
    }
}

watchDebounced([searchInput], fetchRooms, {
    debounce: 500,
    maxWait: 1000,
    immediate: true,
})
</script>

<template>
    <view
        :style="{
            paddingTop: `${safeAreaInsets.top + menuButton?.height ?? 0}px`,
        }"
    >
        <view
            class="mx-2 my-2 flex h-14 items-center rounded-full bg-zinc-100 px-4"
        >
            <uni-icons
                font-family="heroicons-outline"
                :size="20"
                class="mr-3"
                color="#4b5563"
                @click="goBack"
            >
                {{ '\ue911' }}
            </uni-icons>
            <input
                v-model="searchInput"
                class="h-14 w-full"
                focus
                :placeholder="t('search')"
            />
        </view>
        <view>
            <navigator
                v-for="room in showRoomList"
                :key="room.id"
                :url="`/pages/index/index?room=${room.id}`"
            >
                <view class="p-3">
                    {{ room.roomName ?? '新的对话' }}
                </view>
            </navigator>
        </view>
    </view>
</template>
